#include "machine_control.h"
#include <stdio.h>
#include <unistd.h>

// 打印设备状态信息
void print_machine_state(void) {
    const DeviceState* state = machine_get_state();
    const SensorData* sensors = machine_get_sensors();
    
    printf("\n=== Machine State ===\n");
    printf("Mode: ");
    switch (state->current_mode) {
        case MODE_STANDBY: printf("Standby"); break;
        case MODE_COOLING: printf("Cooling"); break;
        case MODE_CLEANING: printf("Cleaning"); break;
        case MODE_DEFROST: printf("Defrost"); break;
        case MODE_PRESERVATION: printf("Preservation"); break;
        default: printf("Unknown");
    }
    printf(" (Runtime: %ds)\n", state->mode_runtime);
    
    printf("Temperatures: Cabinet=%.1f°C, Material=%.1f°C\n",
           sensors->cabinet_temp, sensors->material_temp);
    printf("Motor: %s (Current: %dmA)\n",
           state->motor_running ? "Running" : "Stopped",
           sensors->motor_current);
    printf("Compressor: %s, Bypass valve: %s\n",
           state->comp_running ? "On" : "Off",
           state->bypass_valve ? "On" : "Off");
    
    if (state->in_error) {
        printf("Error: Code %d\n", state->error_code);
    }
    printf("=====================\n");
}

int main(void) {
    printf("Automatic Ice Cream Machine Controller\n");
    printf("=====================================\n");
    
    // 初始化设备
    machine_init();
    
    // 模拟运行过程
    printf("\n=== Starting mode sequence ===\n");
    
    // 待机模式
    printf("\n[1] Standby mode (5 seconds)\n");
    for (int i = 0; i < 5; i++) {
        machine_run_handler();
        sleep(1);
    }
    print_machine_state();
    
    // 制冷模式
    machine_set_mode(MODE_COOLING);
    printf("\n[2] Cooling mode (20 seconds)\n");
    for (int i = 0; i < 20; i++) {
        machine_run_handler();
        sleep(1);
    }
    print_machine_state();
    
    // 保鲜模式
    machine_set_mode(MODE_PRESERVATION);
    printf("\n[3] Preservation mode (15 seconds)\n");
    for (int i = 0; i < 15; i++) {
        machine_run_handler();
        sleep(1);
    }
    print_machine_state();
    
    // 解冻模式
    machine_set_mode(MODE_DEFROST);
    printf("\n[4] Defrost mode (15 seconds)\n");
    for (int i = 0; i < 15; i++) {
        machine_run_handler();
        sleep(1);
    }
    print_machine_state();
    
    // 清洗模式
    machine_set_mode(MODE_CLEANING);
    printf("\n[5] Cleaning mode (20 seconds)\n");
    for (int i = 0; i < 20; i++) {
        machine_run_handler();
        sleep(1);
    }
    print_machine_state();
    
    // 返回待机模式
    machine_set_mode(MODE_STANDBY);
    printf("\n[6] Return to standby mode\n");
    sleep(5);
    print_machine_state();
    
    printf("\n=== Test completed ===\n");
    return 0;
}
